package com.hnhs.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hnhs.info.ImageInfo;
import com.hnhs.info.UploadInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/upload")   
public class UploadController {
    //图片上传
    @PostMapping
    public String upload(@RequestBody UploadInfo uploadInfo){
        String name=uploadInfo.getName();
        String base64 = uploadInfo.getBase64();
        //切割字符串 base64  从base64，返回一个数组
        String[] base64s= StrUtil.splitToArray(base64,"base64,");
        //转换byte数组
        byte[] bytes=Base64.decode(base64s[1]);
        name=IdUtil.getSnowflakeNextIdStr()+"_"+name;
        System.out.println(name);
        //写入到nginx
        FileUtil.writeBytes(bytes,"D:/software/nginx-1.21.4/html/images/"+name);



        return "http://www.lz.com/images/"+name;
    }

    //图片获取
    @GetMapping
    public List<ImageInfo> get(){
    List<String> fileName=FileUtil.listFileNames("D:/software/nginx-1.21.4/html/images/");
        List<ImageInfo> collect = fileName.stream().map(
                item -> {
                    return new ImageInfo(item, "http://www.lz.com/images/" + item);
                }
        ).collect(Collectors.toList());


        return collect;
    }
}
